package com.tongfusoft.document.web.controller.doc;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.tongfusoft.da.pagehelper.PageInfo;
import com.tongfusoft.document.doc.service.IAdvancedSearchService;
import com.tongfusoft.document.doc.service.IDocAuthenticationService;
import com.tongfusoft.document.doc.service.IDocService;
import com.tongfusoft.document.doc.service.IFileStroageService;
import com.tongfusoft.document.entity.DocHistory;
import com.tongfusoft.document.entity.Docs;
import com.tongfusoft.document.entity.UserFavorites;
import com.tongfusoft.document.entity.UserFollows;
import com.tongfusoft.document.entity.Users;
import com.tongfusoft.document.manager.dictionary.service.IDocumentDictionaryService;
import com.tongfusoft.document.manager.metadata.service.IMetadataService;
import com.tongfusoft.document.manager.profile.service.InputProfileService;
import com.tongfusoft.document.personalCenter.myFavorite.service.IMyFavoriteService;
import com.tongfusoft.document.personalCenter.myFollow.service.IMyFollowService;
import com.tongfusoft.document.utils.DocContent;
import com.tongfusoft.exception.ServiceException;
import com.tongfusoft.spring.web.core.controller.BaseController;
import com.tongfusoft.spring.web.core.controller.annotation.UrlDesc;
import com.tongfusoft.spring.web.core.data.ResultModel;
import com.tongfusoft.utils.Constant;
import com.tongfusoft.utils.JsonUtils;

@Controller
public class DocController extends BaseController {

	@Autowired
	public IDocService docService;

	@Autowired
	public IFileStroageService fileStroageService;

	@Autowired
	@Qualifier("documentDictionaryService")
	public IDocumentDictionaryService dDictionaryService;

	@Autowired
	@Qualifier("metaDataManagerService")
	public IMetadataService mMService;

	@Autowired
	@Qualifier("profileService")
	public InputProfileService profileService;

	@Autowired
	public IDocAuthenticationService docAuthenticationService;

	@Autowired
	@Qualifier("iMyFavoriteService")
	public IMyFavoriteService iMyFavoriteService;

	@Autowired
	@Qualifier("userFollowService")
	public IMyFollowService userFollowService;

	@RequestMapping("/mydoc")
	@UrlDesc(value = "我的文档列表页")
	public String myDocPage(Model model) {

		model.addAttribute("mainPageKey", "myDocList");
		model.addAttribute("mainPage", "doc/myDocList");
		model.addAttribute("queryText", "");
		model.addAttribute("profileList", this.profileService.validProfile());

		return "base";

	}

	@RequestMapping("/mydoc/query")
	@UrlDesc(value = "我的文档查询")
	@ResponseBody
	public PageInfo systemParamQuery(Model model, int pageIndex, int pageSize, String query) {
		PageInfo pageInfo = new PageInfo();
		try {
			Docs doc = new Docs();
			doc.setCreatedBy(((Users) super.getUser()).getUserId());

			if (StringUtils.isNotEmpty(query)) {
				Map queryMap = JsonUtils.getMap4Json(query);
				if (queryMap.get("fastText") != null) {

					doc.setDocTitle(queryMap.get("fastText").toString());
					doc.setDocSummary(queryMap.get("fastText").toString());
					doc.setOriginalName(queryMap.get("fastText").toString());
				}
			}

			pageInfo = this.docService.searchDoc(doc, (Users) super.getUser(), pageSize, pageIndex);

		} catch (Exception e) {

			e.printStackTrace();
		}
		return pageInfo;

	}

	@RequestMapping("/docDel/{docName}")
	@UrlDesc(value = "文档删除")
	@ResponseBody
	public ResultModel docDel(Model model, String docId, @PathVariable("docName") String docName) {

		ResultModel rm = new ResultModel();
		try {

			if (this.docAuthenticationService.isDelete(this.docAuthenticationService.getGroupId(docName, docId),
					(Users) super.getUser())) {
				this.docService.deleteDoc(docName, docId, (Users) super.getUser());
				rm.setState("success");
			} else {
				rm.setState("error");
				rm.setCode("delete_power_error");
			}

		} catch (ServiceException se) {

			rm.setState("error");
			rm.setCode(se.getMessage());

		} catch (Exception e) {
			rm.setState("error");
			e.printStackTrace();
		}
		return rm;

	}

	@RequestMapping("/docCheckIn")
	@UrlDesc(value = "文档新增页")
	public String checkInPage(Model model) {

		model.addAttribute("mainPageKey", "docCheckIn");
		model.addAttribute("mainPage", "doc/docCheckIn");
		model.addAttribute("displayName", ((Users) super.getUser()).getDisplayName());
		model.addAttribute("docTypeList", this.dDictionaryService.getDictByCode("docType"));
		model.addAttribute("groupList", this.docService.docEditGroupByUser(((Users) super.getUser()).getUserId()));
		model.addAttribute("metaDateList", this.mMService.getIsEnableMeta());
		return "base";

	}

	@UrlDesc(value = "更新文档页")
	@RequestMapping("/docUpdate/{returnPage}/{docName}")
	public String docUpdatePage(Model model, @PathVariable("docName") String docName,
			@PathVariable("returnPage") String returnPage) {

		Docs doc = new Docs();

		doc.setDocName(docName);
		if (this.docAuthenticationService.isWrite(this.docAuthenticationService.getGroupId(docName, ""),
				(Users) super.getUser())) {
			model.addAttribute("returnPage", DocContent.getReturnPage(returnPage));
			String profileId = this.docService.profileId(docName);
			model.addAttribute("docTypeList", this.dDictionaryService.getDictByCode("docType"));
			model.addAttribute("groupList", this.docService.docEditGroupByUser(((Users) super.getUser()).getUserId()));
			model.addAttribute("docName", docName);
			if (StringUtils.isEmpty(profileId)) {
				model.addAttribute("mainPageKey", "docUpdate");
				model.addAttribute("mainPage", "doc/docUpdate");
				model.addAttribute("metaDateList", this.mMService.getIsEnableMeta());

			} else {
				model.addAttribute("mainPageKey", "profileDocUpdate");
				model.addAttribute("mainPage", "doc/profileDocUpdate");
				model.addAttribute("profileId", profileId);
				model.addAttribute("filesetList", this.mMService.getIsEnableMetaByProFile(profileId));

			}
		} else {
			model.addAttribute("docName", docName);
			return "redirect:/error/docUpdateError";
		}
		return "base";

	}

	@UrlDesc(value = "文档新增模版页")
	@RequestMapping("/docCheckIn/{profileId}")
	public String profileCheckInPage(@PathVariable("profileId") String profileId, Model model) {

		model.addAttribute("mainPageKey", "profileDocCheckIn");
		model.addAttribute("mainPage", "doc/profileDocCheckIn");
		model.addAttribute("displayName", ((Users) super.getUser()).getDisplayName());
		model.addAttribute("profileId", profileId);
		model.addAttribute("groupList", this.docService.docEditGroupByUser(((Users) super.getUser()).getUserId()));
		model.addAttribute("docTypeList", this.dDictionaryService.getDictByCode("docType"));
		model.addAttribute("filesetList", this.mMService.getIsEnableMetaByProFile(profileId));
		return "base";

	}

	@UrlDesc(value = "文档详情页")
	@RequestMapping("/docView/{returnPage}/{docName}")
	public String docView(@PathVariable("returnPage") String returnPage, @PathVariable("docName") String docName,
			String docId, Model model) {

		DocHistory doc = new DocHistory();
		doc.setDocName(docName);
		doc.setDocId(docId);

		if (this.docAuthenticationService.isRead(this.docAuthenticationService.getGroupId(docName, docId),
				(Users) super.getUser())) {
			model.addAttribute("docName", docName);
			model.addAttribute("docId", docId);
			model.addAttribute("mainPageKey", "docDetail");
			model.addAttribute("mainPage", "doc/docDetail");
			model.addAttribute("metaDateList", this.mMService.getIsEnableMeta());
			
			//从文件夹过来详情页
			if(returnPage.equals("fileDirectory")){
				Docs d= new Docs();
				d.setDocName(docName);
				model.addAttribute("returnPage", DocContent.getReturnPage(returnPage)+"/"+this.docService.getDoc(d,(Users)super.getUser()).getDocFolder());
			}else{
				
				model.addAttribute("returnPage", DocContent.getReturnPage(returnPage));
			}
		} else {

			model.addAttribute("docName", docName);
			return "redirect:/error/docViewDetail";

		}
		return "base";

	}

	@UrlDesc(value = "新增文档保存")
	@RequestMapping("/docCheckIn/upload")
	@ResponseBody
	public ResultModel upload(MultipartFile file, Docs doc, String docMetadata) {

		ResultModel rm = new ResultModel();

		doc.setDocMetadata(docMetadata);
		rm.setState("success");
		try {
			if (this.docAuthenticationService.isWrite(doc.getDocGroup(), (Users) super.getUser())) {

				Map<String, String> metaDataMap = JsonUtils.getMap4Json(docMetadata);

				doc.setUploadModel(metaDataMap.get("uploadMode"));
				doc.setSelectFileId(metaDataMap.get("selectFileId") == null ? "" : metaDataMap.get("selectFileId"));
				this.docService.createDoc(file, doc, (Users) super.getUser());
			} else {
				rm.setState("error");
				rm.setCode("write_power_error");
			}

		} catch (Exception e) {
			rm.setState("error");
		}

		return rm;

	}

	@UrlDesc(value = "更新文档保存")
	@RequestMapping("/docUpdate/upload")
	@ResponseBody
	public ResultModel docUpdate(MultipartFile file, Docs doc, String docMetadata) {

		ResultModel rm = new ResultModel();

		doc.setDocMetadata(docMetadata);

		try {
			if (this.docAuthenticationService.isWrite(this.docAuthenticationService.getGroupId(doc.getDocName(), ""),
					(Users) super.getUser())) {
				Map<String, String> metaDataMap = JsonUtils.getMap4Json(docMetadata);

				doc.setUploadModel(metaDataMap.get("uploadMode"));
				doc.setSelectFileId(metaDataMap.get("selectFileId") == null ? "" : metaDataMap.get("selectFileId"));
				this.docService.updateDoc(file, doc, (Users) super.getUser());
				rm.setState("success");
			} else {
				rm.setState("error");
				rm.setCode("write_power_error");
			}

		} catch (Exception e) {
			rm.setState("error");
		}

		return rm;

	}

	@UrlDesc(value = "更新页获取文档信息")
	@RequestMapping("/docDetail/update/{docName}")
	@ResponseBody
	public ResultModel updateDocDetail(@PathVariable("docName") String docName) {
		ResultModel rm = new ResultModel();
		Docs doc = new Docs();
		doc.setDocName(docName);
		rm.setState("success");
		try {
			doc = this.docService.getDoc(doc, (Users) super.getUser());
			doc.setDocPath("");
			rm.setData(doc);

		} catch (Exception e) {
			rm.setState("error");
		}

		return rm;

	}

	@UrlDesc(value = "文档详情")
	@RequestMapping("/docDetail/view/{docName}")
	@ResponseBody
	public ResultModel viewDocDetail(@PathVariable("docName") String docName, String docId) {
		ResultModel rm = new ResultModel();
		DocHistory doc = new DocHistory();
		doc.setDocName(docName);
		doc.setDocId(docId);
		rm.setState("success");
		Map docMap = new HashMap();
		try {

			DocHistory detail = this.docService.viewDocDetail(doc, (Users) super.getUser());

			if (this.docAuthenticationService.isRead(this.docAuthenticationService.getGroupId(docName, docId),
					(Users) super.getUser())) {

				if (detail != null) {
					detail.setDocPath("");
					docMap.put("docData", detail);
					docMap.put("docHistory", this.docService.DocsHistoryList(doc.getDocName()));
					rm.setData(docMap);
				} else {

					rm.setCode("detail_null");
				}

			} else {

				rm.setState("error");
				rm.setCode("read_power_error");

			}

		} catch (Exception e) {
			e.printStackTrace();
			rm.setState("error");
		}

		return rm;

	}

	@UrlDesc(value = "文档下载")
	@RequestMapping(value = "/download/{docName}")
	public void downloadFile(HttpServletRequest request, HttpServletResponse response, String docId, Model model,
			@PathVariable("docName") String docName) {

		if (!this.docAuthenticationService.isRead(this.docAuthenticationService.getGroupId(docName, docId),
				(Users) super.getUser())) {

			model.addAttribute("docName", docName);
			try {
				response.sendRedirect(request.getContextPath() + "/error/docViewDetail");
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		try {
			request.setCharacterEncoding("utf-8");
		} catch (UnsupportedEncodingException e2) {
			e2.printStackTrace();
		}
		response.setCharacterEncoding("utf-8");
		response.setContentType("multipart/form-data");
		String filePath = null;
		InputStream inputStream = null;
		OutputStream os = null;
		DocHistory doch = new DocHistory();
		try {

			doch.setDocName(docName);
			doch.setDocId(docId);

			doch = this.docService.viewDocDetail(doch, (Users) super.getUser());
			String fileName = doch.getOriginalName();
			String userAgent = request.getHeader("User-Agent");
			byte[] bytes = userAgent.contains("MSIE") ? fileName.getBytes() : fileName.getBytes("UTF-8"); // fileName.getBytes("UTF-8")处理safari的乱码问题
			fileName = new String(bytes, "ISO-8859-1"); // 各浏览器基本都支持ISO编码
			response.setHeader("Content-disposition", String.format("attachment; filename=\"%s\"", fileName));
			response.setHeader("Content-Length", String.valueOf(doch.getDocSize()));

		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		}
		try {

			inputStream = this.fileStroageService.read(doch);
			os = response.getOutputStream();
			byte[] b = new byte[1024];
			int length = 0;
			while ((length = inputStream.read(b)) > 0) {
				os.write(b, 0, length);
			}

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (os != null) {
					os.close();
				}
				if (inputStream != null) {
					inputStream.close();
				}

			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	@UrlDesc(value = "判断文档收藏状态")
	@RequestMapping("/isUserFavorite")
	@ResponseBody
	public ResultModel isUserFavorite(HttpServletRequest request, String docName, String createdBy) {

		ResultModel rm = new ResultModel();

		try {
			HttpSession session = request.getSession();
			UserFavorites favorites = new UserFavorites();
			favorites.setDocName(docName);
			Users user = (Users) session.getAttribute(Constant.SESSION_USER);
			favorites.setCreatedBy(user.getUserId());
			if (this.iMyFavoriteService.getUserFavorite(favorites) != null) {
				rm.setState("success");
			}
		} catch (Exception e) {
			rm.setState("error");
		}

		return rm;

	}

	@UrlDesc(value = "添加收藏")
	@RequestMapping("/createUserFavorite")
	@ResponseBody
	public ResultModel createUserFavorite(String docName) {

		ResultModel rm = new ResultModel();
		rm.setState("success");
		try {
			UserFavorites favorites = new UserFavorites();
			favorites.setDocName(docName);
			this.iMyFavoriteService.createUserFavorites(favorites, (Users) super.getUser());

		} catch (ServiceException se) {

			rm.setState("error");
			rm.setCode(se.getMessage());

		} catch (Exception e) {
			rm.setState("error");
			e.printStackTrace();
		}

		return rm;

	}

	@UrlDesc(value = "取消收藏")
	@RequestMapping("/deleteFavoriteBtn")
	@ResponseBody
	public ResultModel deleteFavoriteBtn(String docName) {

		ResultModel rm = new ResultModel();
		rm.setState("success");
		try {
			UserFavorites favorites = new UserFavorites();
			favorites.setDocName(docName);
			this.iMyFavoriteService.deleteUserFavorites(favorites);

		} catch (ServiceException se) {

			rm.setState("error");
			rm.setCode(se.getMessage());

		} catch (Exception e) {
			rm.setState("error");
			e.printStackTrace();
		}
		return rm;
	}

	/**
	 * 判断是否已被关注
	 * 
	 * @param docName
	 * @return
	 */
	@UrlDesc(value = "判断文档关注状态")
	@RequestMapping("/isUserFollower")
	@ResponseBody
	public ResultModel userFollowsGet(Model model, UserFollows userFollows, String createdBy) {

		ResultModel rm = new ResultModel();
		try {
			userFollows.setCreatedBy(createdBy);
			if (this.userFollowService.getUserFollow(userFollows) != null) {
				rm.setState("success");
			}

		} catch (ServiceException se) {

			rm.setState("error");
			rm.setCode(se.getMessage());

		} catch (Exception e) {
			rm.setState("error");
			e.printStackTrace();
		}
		return rm;

	}

	/**
	 * 添加关注
	 * 
	 * @param docName
	 * @return
	 */
	@UrlDesc(value = "添加关注")
	@RequestMapping("/userFollows/add/{docName}")
	@ResponseBody
	public ResultModel userFollowsAdd(@PathVariable("docName") String docName, Model model, UserFollows userFollows) {

		ResultModel rm = new ResultModel();
		try {
			userFollows.setDocName(docName);
			this.userFollowService.createUserFollow(userFollows, (Users) super.getUser());
			rm.setState("success");
		} catch (ServiceException se) {

			rm.setState("error");
			rm.setCode(se.getMessage());

		} catch (Exception e) {
			rm.setState("error");
			e.printStackTrace();
		}
		return rm;

	}

	/**
	 * 取消关注
	 * 
	 * @param docName
	 * @return
	 */
	@UrlDesc(value = "取消关注")
	@RequestMapping("/userFollows/del/{docName}")
	@ResponseBody
	public ResultModel userFollowsDel(@PathVariable("docName") String docName, Model model, UserFollows userFollows) {

		ResultModel rm = new ResultModel();
		try {
			userFollows.setDocName(docName);
			this.userFollowService.delUserFollowDoc(userFollows, (Users) super.getUser());
			rm.setState("success");
		} catch (ServiceException se) {

			rm.setState("error");
			rm.setCode(se.getMessage());

		} catch (Exception e) {
			rm.setState("error");
			e.printStackTrace();
		}
		return rm;

	}
}
